import pandas as pd
file='item4/wine.data'
names=['label', 'a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13']
dataset=pd.read_csv(file ,names=names)
print("葡萄酒数据集如下:")
print(dataset)
#分别提取数据集的特征变量与标签
data=dataset.iloc[range(0,178),range(1,14)]
target=dataset.iloc[range(0,178),range(0,1)]
print(f'特征数组的形状:{data.shape}')
print(f'特征数组的形状')


import matplotlib.pyplot as plt
plt.style.use('seaborn-darkgrid')
plt.rcParams['axes.unicode minus']=False#正常显示负号
data.plot(kind='box',subplots=True,layout=(3,5),sharex=False,sharey=False)#查找异常数据并输出
p=data.boxplot(return_type='dict')
for i in range(13):
    y=p['fliers'][i].get_ydata()
    print('a',i+1,'中异常值:',y)
plt.show()


import pandas as pd
from sklearn import preprocessing
#导入数据，分别提取数据集的特征变量与标签
names=['label','a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13']
dataset=pd.read_csv("wine-clean.data",names=names)
data=dataset.iloc[range(0,178),range(1,14)]
target=dataset.iloc[range(0,178),range(0,1)].values.reshape(1,178)[0]
#使用z-score方法进行数据标准化处理
cdata=preprocessing.StandardScaler().fit_transform(data)
print(cdata)


#导入需要的库
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
#将特征变量与标签分别赋值给x和y，并将数据集拆分为训练集与测试集#导入交又验证模块
x,y=cdata,target
x_train,x_test,y_train,y_test=train_test_split(x,yrandom_state=0)
#k取不同值的情况下，模型的预测误差率计算
k_range=range(1.15)#设置k值的取值范围
k_error=[]#保存预测误差率的数组
for k in k_range:
    model=KNeighborsClassifier(n_neighbors=k)
    scores=cross_val_score(model,x,y,cv=5,scoring='accuracy')#5折交叉验证
k_error.append(1-scores.mean())
#画图，x轴表示k的取值，y轴表示预测误差率
plt.rcParams['font.sans-serif']='Simhei'
plt.plot(k_range,k_error,'r-')
plt.xlabel('k的取值')
plt.ylabel('预测误差率')
plt.show()


from sklearn.metrics import accuracy_score
#k=9时，训练模型
model=KNeighborsClassifier(n_neighbors=9)
model.fit(x_train,y_train)
#对模型进行评估
pred=model.predict(x_test)
ac=accuracy_score(y_test,pred)
print("模型预测准确率:",ac)
print("测试集的预测标签:",pred)
print("测试集的真实标签:",y_test)